package org.example.modules.user.service.Impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.example.common.utils.ThreadLocalUtil;
import org.example.modules.user.common.Commsult;
import org.example.modules.user.entry.UserWallet;
import org.example.modules.user.entry.WalletDetails;
import org.example.modules.user.mapper.UserWalletMapper;
import org.example.modules.user.mapper.WalletDetailsMapper;
import org.example.modules.user.service.UserWalletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;

/**
 * @Description UserWalletServiceImpl
 * @Author xiaotian
 * @Date 2025-04-20
 */
@Service
@Slf4j
public class UserWalletServiceImpl extends ServiceImpl<UserWalletMapper, UserWallet> implements UserWalletService {
    @Autowired
    private UserWalletMapper userWalletMapper;

    @Autowired
    private WalletDetailsMapper walletDetailsMapper;

    @Override
    public UserWallet getWalletBalance(String userName) {
        QueryWrapper<UserWallet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userName);
        UserWallet wallet = userWalletMapper.selectOne(queryWrapper);
        if (wallet == null) {
            throw new RuntimeException("用户钱包不存在");
        }
        UserWallet dto = new UserWallet();
        dto.setUserName(wallet.getUserName());
        dto.setMoney(wallet.getMoney());
        return dto;
    }

    @Transactional
    @Override
    public void recharge(JSONObject request) {
        UserWallet wallet = findOrCreateWallet(ThreadLocalUtil.getUserId());
        BigDecimal rechargeAmount = request.getBigDecimal("amount");
        wallet.setBeforeMonry(wallet.getMoney());
        wallet.setMoney(wallet.getMoney().add(rechargeAmount));
        wallet.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        WalletDetails walletDetails = new WalletDetails();
        walletDetails.setWalletId(wallet.getId());
        walletDetails.setTransactionAmount(rechargeAmount);
        walletDetails.setType(1);
        walletDetails.setTransactionTime(wallet.getUpdateTime());
        walletDetails.setAccountType(request.getString("accountType").equals("wechat") ? "微信充值" : "支付宝充值");
        if(request.getString("accountType").equals("back")){
            walletDetails.setAccountType("取消订单");
            walletDetails.setType(4);
        }
        userWalletMapper.updateById(wallet);
        walletDetailsMapper.insert(walletDetails);
    }

    @Override
    public void withdraw(JSONObject request) {
        // 获取用户的钱包信息，不存在则创建
        UserWallet wallet = findOrCreateWallet(ThreadLocalUtil.getUserId());
        BigDecimal withdrawAmount = request.getBigDecimal("amount");

        // 检查余额是否足够
        if (wallet.getMoney().compareTo(withdrawAmount) < 0) {
            throw new RuntimeException("余额不足");
        }

        // 更新钱包前金额和当前金额
        wallet.setBeforeMonry(wallet.getMoney());
        wallet.setMoney(wallet.getMoney().subtract(withdrawAmount));

        // 设置更新时间
        String updateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        wallet.setUpdateTime(updateTime);

        // 创建并设置WalletDetails对象的值
        WalletDetails walletDetails = new WalletDetails();
        walletDetails.setWalletId(wallet.getId());
        walletDetails.setTransactionAmount(withdrawAmount);
        walletDetails.setType(2); // 假设2表示提现
        walletDetails.setTransactionTime(updateTime);
        walletDetails.setAccountType(request.getString("accountType").equals("wechat") ? "微信提现" : "支付宝提现");

        // 更新数据库中的钱包信息
        userWalletMapper.updateById(wallet);

        // 插入新的交易记录
        walletDetailsMapper.insert(walletDetails);
    }

    @Override
    public List<WalletDetails> getWalletDetails() {
        String userName = ThreadLocalUtil.getUserId();
        List<WalletDetails> walletDetails =  userWalletMapper.getWalletDetails(userName);
        return walletDetails;
    }

    @Override
    public Integer orderPay(BigDecimal amount) {
        UserWallet wallet = userWalletMapper.getWallet(ThreadLocalUtil.getUserId());
        if(wallet.getMoney()==null||wallet.getMoney().compareTo(amount) < 0){
            return 0;
        }
        wallet.setBeforeMonry(wallet.getMoney());
        wallet.setMoney(wallet.getMoney().subtract(amount));
        wallet.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        WalletDetails walletDetails = new WalletDetails();
        walletDetails.setWalletId(wallet.getId());
        walletDetails.setTransactionAmount(amount);
        walletDetails.setType(3);
        walletDetails.setTransactionTime(wallet.getUpdateTime());
        walletDetails.setAccountType("订单支付");
        userWalletMapper.updateById(wallet);
        walletDetailsMapper.insert(walletDetails);
        return 1;
    }

    private UserWallet findOrCreateWallet(String userName) {
        QueryWrapper<UserWallet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userName);
        UserWallet wallet = userWalletMapper.selectOne(queryWrapper);
        if (wallet == null) {
            wallet = new UserWallet();
            wallet.setUserName(userName);
            wallet.setMoney(BigDecimal.ZERO);
            wallet.setBeforeMonry(BigDecimal.ZERO);
            wallet.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            userWalletMapper.insert(wallet);
        }
        return wallet;
    }
}

